package com.shenmazong.servernewsapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shenmazong.MongoServiceAd;
import com.shenmazong.TbService;
import com.shenmazong.servernewsapi.service.NewsMongoService;
import com.shenmazong.utils.ConstUtils;
import com.shenmazong.utils.ResponseResult;
import com.shenmazong.utils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class NewsMongoServiceImpl implements NewsMongoService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResponseResult addUserNews(Integer userId, Double longitude, Double latitude, Integer serviceType, String Title, String content) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 写入数据库
        MongoServiceAd news = new MongoServiceAd();
        news.setUserid(userId);
        news.setLongitude(longitude);
        news.setLatitude(latitude);
        news.setServicetype(serviceType);
        news.setTitle(Title);
        news.setContent(content);

        SnowFlake snowFlake = new SnowFlake(2, 3);
        long newsId = snowFlake.nextId();
        news.setId(newsId);

        mongoTemplate.save(news);
        //tbServiceMapper.insert(news);

        //--2 写入到redis geo中
        RedisGeoCommands.GeoLocation<Integer> longGeoLocation = new RedisGeoCommands.GeoLocation<>(userId, new Point(longitude, latitude));
        redisTemplate.opsForGeo().add(ConstUtils.USER_GEO_ZSET_NAME, longGeoLocation);

        return result;
    }

    @Override
    public ResponseResult delUserNewsById(Integer userId, Long newsId) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--
        Query query = new Query(Criteria.where("id").is(newsId));
        MongoServiceAd news =  mongoTemplate.findOne(query , MongoServiceAd.class);
        if(news == null) {
            result.setCode(-1);
            result.setMessage("信息不存在");
            return result;
        }

        if(!news.getUserid().equals(userId)) {
            result.setCode(-1);
            result.setMessage("没有删除权限");
            return result;
        }

        mongoTemplate.remove(query, MongoServiceAd.class);
        //tbServiceMapper.deleteById(newsId);

        return result;
    }

    @Override
    public ResponseResult setUserNews(Integer userId, Long newsId, Double longitude, Double latitude, Integer serviceType, String title, String content) {
        ResponseResult result = ResponseResult.SUCCESS();

        //--1 检查新闻在不在
        Query query = new Query(Criteria.where("id").is(newsId));
        MongoServiceAd news =  mongoTemplate.findOne(query , MongoServiceAd.class);
        //TbService news = tbServiceMapper.selectById(newsId);
        if(news == null) {
            result.setCode(-1);
            result.setMessage("信息不存在");
            return result;
        }

        //--2 检查权限
        if(!news.getUserid().equals(userId)) {
            result.setCode(-1);
            result.setMessage("没有删除权限");
            return result;
        }

        //--3 修改信息
        news.setLongitude(longitude);
        news.setLatitude(latitude);
        news.setServicetype(serviceType);
        news.setTitle(title);
        news.setContent(content);
        //tbServiceMapper.updateById(news);
        mongoTemplate.save(news);

        //--4 写入到redis geo中
        RedisGeoCommands.GeoLocation<Integer> longGeoLocation = new RedisGeoCommands.GeoLocation<>(userId, new Point(longitude, latitude));
        redisTemplate.opsForGeo().add(ConstUtils.USER_GEO_ZSET_NAME, longGeoLocation);

        return result;
    }

    @Override
    public ResponseResult getNewsByUserId(Integer userId, Integer pageNo, Integer pageSize) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> dataMap = new HashMap<>();

        //--1 分页信息
        //-- 获取记录偏移量
        if(pageNo < 1) pageNo = 1;
        long offset = (pageNo-1) * pageSize;

        //--2 设置查询条件
        Query query = new Query(Criteria.where("userid").is(userId));

        //-- 获取总的记录数
        long count = mongoTemplate.count(query, MongoServiceAd.class);
        if(count == 0L) {
            result.setCode(-1);
            result.setMessage("没有数据");
            return result;
        }


        //-- 确定分页查询条件
        query.with(Sort.by(Sort.Order.desc("id")));
        query.skip(offset).limit(pageSize); // 分页逻辑

        //--3 信息查询
        List<MongoServiceAd> shopMongoOrders = mongoTemplate.find(query, MongoServiceAd.class);
        if(shopMongoOrders == null) {
            result.setCode(-1);
            result.setMessage("没有分页数据");
            return result;
        }

        //--4 设置返回数据
        dataMap.put("totalCount", count);
        dataMap.put("currentPage", pageNo);
        dataMap.put("pageSize", pageSize);
        dataMap.put("count", shopMongoOrders.size());
        dataMap.put("news", shopMongoOrders);

        result.setResult(dataMap);

        return result;
    }

    @Override
    public ResponseResult getNewsByTypeId(Integer userId, Integer typeId, Integer pageNo, Integer pageSize) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> dataMap = new HashMap<>();

        //--1 分页信息
        //-- 获取记录偏移量
        if(pageNo < 1) pageNo = 1;
        long offset = (pageNo-1) * pageSize;

        //--2 设置查询条件
        Query query = new Query(Criteria.where("servicetype").is(typeId));

        //-- 获取总的记录数
        long count = mongoTemplate.count(query, MongoServiceAd.class);
        if(count == 0L) {
            result.setCode(-1);
            result.setMessage("没有数据");
            return result;
        }


        //-- 确定分页查询条件
        query.with(Sort.by(Sort.Order.desc("id")));
        query.skip(offset).limit(pageSize); // 分页逻辑

        //--3 信息查询
        List<MongoServiceAd> shopMongoOrders = mongoTemplate.find(query, MongoServiceAd.class);
        if(shopMongoOrders == null) {
            result.setCode(-1);
            result.setMessage("没有分页数据");
            return result;
        }

        //--4 设置返回数据
        dataMap.put("totalCount", count);
        dataMap.put("currentPage", pageNo);
        dataMap.put("pageSize", pageSize);
        dataMap.put("count", shopMongoOrders.size());
        dataMap.put("news", shopMongoOrders);

        result.setResult(dataMap);

        return result;
    }
}
